package com.htd.htdapmcommon.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpUtils {

	//private static Logger LOG = Logger.getLogger(HttpUtils.class);
	private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);

	
	public HttpUtils() {
	}

	/*
	 * params 填写的URL的参数 encode 字节编码
	 */
	public static String sendPostMessage(Map<String, String> params,String encode,String path) {
		LOG.info("调动http接口开始:");
		URL url = null;
		try {
			url = new URL(path);
		} catch (MalformedURLException e1) {
			LOG.error("URL出现异常：{}",e1);
			return "";
		};
		StringBuffer stringBuffer = new StringBuffer();
		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				try {
					stringBuffer
							.append(entry.getKey())
							.append("=")
							.append(URLEncoder.encode(entry.getValue(), encode))
							.append("&");
				} catch (UnsupportedEncodingException e) {
					LOG.error("stringBuffer拼接参数异常：",e);
					return "";
				}
			}
			// 删掉最后一个 & 字符
			stringBuffer.deleteCharAt(stringBuffer.length() - 1);
			HttpURLConnection httpURLConnection = null;
			try {
				httpURLConnection = (HttpURLConnection) url.openConnection();
				httpURLConnection.setConnectTimeout(5000);
				httpURLConnection.setReadTimeout(10000);
				httpURLConnection.setDoInput(true);// 从服务器获取数据
				httpURLConnection.setDoOutput(true);// 向服务器写入数据

				// 获得上传信息的字节大小及长度
				byte[] mydata = stringBuffer.toString().getBytes();
				// 设置请求体的类型
				httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
				httpURLConnection.setRequestProperty("Content-Lenth",String.valueOf(mydata.length));

				// 获得输出流，向服务器输出数据
				OutputStream outputStream = (OutputStream) httpURLConnection.getOutputStream();
				outputStream.write(mydata);
				outputStream.flush();// 强制把缓冲区的数据写入到文件并清空缓冲区
				outputStream.close();// 关闭连接
				// 获得服务器响应的结果和状态码
				int responseCode = httpURLConnection.getResponseCode();
				LOG.info("调动http接口返回responseCode:{}",responseCode);
				if (responseCode == 200) {
					// 获得输入流，从服务器端获得数据
					InputStream inputStream = (InputStream) httpURLConnection.getInputStream();
					return (changeInputStream(inputStream, encode));
				}else{
					LOG.info("获得服务器响应结果:{}"+httpURLConnection.getResponseMessage());
					LOG.info("获得服务器响应结果状态码:{}"+responseCode);
				}
			} catch (IOException e) {
				LOG.error("读写异常：",e);
				return "";
			} finally {
				if (httpURLConnection != null) {
					httpURLConnection.disconnect();
				}
			}
		}
		return "";
	}
	
	public static String sendGetMessage(Map<String, String> params,String encode,String path) {

		StringBuffer stringBuffer = new StringBuffer();

		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				try {
					stringBuffer
							.append(entry.getKey())
							.append("=")
							.append(URLEncoder.encode(entry.getValue(), encode))
							.append("&");
				} catch (UnsupportedEncodingException e) {
					LOG.error("stringBuffer拼接参数异常：{}",e);
					e.printStackTrace();
					return "";
				}
			}
			stringBuffer.deleteCharAt(stringBuffer.length() - 1);
			String GET_URL = path+"?"+stringBuffer.toString();
			LOG.info(GET_URL);
			 HttpURLConnection connection = null;
		    try {
		    	// 把字符串转换为URL请求地址
	            URL url = new URL(GET_URL);    
	            connection = (HttpURLConnection) url.openConnection();// 打开连接
	            // 连接会话
	            connection.connect();
	            InputStream inputStream = (InputStream) connection.getInputStream();
	            return (changeInputStream(inputStream, encode));  
	        } catch (Exception e) {
	        	LOG.error("读写异常：{}",e);
	            return "";
	        }finally {
				if (connection != null) {
					connection.disconnect();
				}
			}
		}	
		return "";	
	}
	
	
	public static String sendPost(String paramsjson,String encode,String path) {
		URL url = null;
		try {
			url = new URL(path);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return "";
		};
		if (paramsjson != null && !paramsjson.isEmpty()) {
	
			HttpURLConnection httpURLConnection = null;
			try {
				httpURLConnection = (HttpURLConnection) url.openConnection();
				httpURLConnection.setConnectTimeout(3000);
				httpURLConnection.setDoInput(true);// 从服务器获取数据
				httpURLConnection.setDoOutput(true);// 向服务器写入数据

				//获得上传信息的字节大小及长度
				byte[] mydata = paramsjson.getBytes();
				//设置请求体的类型
				httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
				httpURLConnection.setRequestProperty("Content-Lenth",String.valueOf(mydata.length));

				//获得输出流，向服务器输出数据
				OutputStream outputStream = (OutputStream) httpURLConnection.getOutputStream();
				outputStream.write(mydata);
				outputStream.flush();// 强制把缓冲区的数据写入到文件并清空缓冲区
				outputStream.close();// 关闭连接
				//获得服务器响应的结果和状态码
				int responseCode = httpURLConnection.getResponseCode();
				if (responseCode == 200) {
					//获得输入流，从服务器端获得数据
					InputStream inputStream = (InputStream) httpURLConnection.getInputStream();
					return (changeInputStream(inputStream, encode).toString());	
				}
			} catch (IOException e) {
				LOG.error("读写异常：{}",e);
				e.printStackTrace();
				return "";
			} finally {
				if (httpURLConnection != null) {
					httpURLConnection.disconnect();
				}
			}
		}
		return "";
	}

	public static String doPost(String reqUrl, String parameters,
			String recvEncoding) {
		LOG.info("***********" + parameters + "**********");
		HttpURLConnection url_con = null;
		String responseContent = null;
		OutputStream os = null;
		try {
			URL url = new URL(reqUrl);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestMethod("POST");
			url_con.setConnectTimeout(100000);
			url_con.setReadTimeout(100000);
			url_con.setDoOutput(true);
			byte[] b = parameters.toString().getBytes(recvEncoding);
			os = url_con.getOutputStream();
			os.write(b, 0, b.length);
			os.flush();
			os.close();

			InputStream in = url_con.getInputStream();
			responseContent = changeInputStream(in, recvEncoding);
			int code = url_con.getResponseCode();
			if (code != 200) {
				responseContent = "ERROR" + code;
			}
		} catch (IOException e) {
			LOG.error("网络故障:",e);
		} finally {
			if (url_con != null) {
				url_con.disconnect();
			}
		}
		return responseContent;
	}

	/*
	 * // 把从输入流InputStream按指定编码格式encode变成字符串String
	 */
	public static String changeInputStream(InputStream inputStream,
			String encode) {

		// ByteArrayOutputStream 一般叫做内存流
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (inputStream != null) {

			try {
				while ((len = inputStream.read(data)) != -1) {
					byteArrayOutputStream.write(data, 0, len);
				}
				result = new String(byteArrayOutputStream.toByteArray(), encode);

			} catch (IOException e) {
				LOG.error("从输入流中获取数据失败",e);
			}
		}
		return result;
	}

	/**
	 * 相关说明：获取post数据 
	 */
	public static String getPostData(HttpServletRequest request) {

		StringBuilder result = new StringBuilder("");

		try {
			BufferedReader br = request.getReader();
			char[] cache = new char[1024];
			int len = 0;
			while((len=br.read(cache))!=-1){
				result.append(cache,0,len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * 相关说明：获取客户端ip 
	 */
	public static String getClientIp(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		ip = (ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip);
		LOG.info("本次登录的用户IP地址：" + ip);
		return ip;
	}

}
